<?php

namespace App\Http\Controllers\rootcontroller\userController;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use App\Models\DawnUser;
use App\Pojo\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use App\Models\DawnZhjyUser;

class UserController extends Controller{

    public function getAllUserDetails(Request $request)
    {
        $request->validate([    
            'keyword' => 'nullable|string',
            'status' => 'nullable|integer',
            'page' => 'required|integer',
            'limit' => 'required|integer',
        ]);
        
        $page = $request->input('page');
        $limit = $request->input('limit');
        
        // 使用with进行关联查询，加载智慧教育用户信息
        // 创建基础查询，使用with预加载关联的智慧教育用户信息，并按创建时间降序排序
        $query = DawnUser::with('zhjyUser')->orderBy("dawn_createTime", "asc");
        
        // 如果存在搜索关键词，则添加搜索条件
        if ($request->has('keyword') && !empty($request->input('keyword'))) {
            $keyword = $request->input('keyword');
            // 使用闭包构建复杂的查询条件
            $query->where(function($q) use ($keyword) {
                // 在基础用户表中搜索用户名
                $q->where('dawn_name', 'like', '%' . $keyword . '%')
                  // 或者在关联的智慧教育用户表中搜索真实姓名或用户名
                  ->orWhereHas('zhjyUser', function($subQuery) use ($keyword) {
                      $subQuery->where('dawn_zhjyIdName', 'like', '%' . $keyword . '%')
                               ->orWhere('dawn_zhjyUser', 'like', '%' . $keyword . '%');
                  });
            });
        }
        
        // 如果存在状态筛选，则添加状态条件
        if ($request->has('status') && $request->input('status') !== null) {
            $status = $request->input('status');
            $query->where('dawn_Status', $status);
        }
        
        // 获取分页数据
        $paginator = $query->paginate($limit, ['*'], 'page', $page);
        
        $data = [
            'list' => $paginator->items(),
            'total' => $paginator->total(),
            'page' => $paginator->currentPage(),
            'limit' => $paginator->perPage(),
            'total_pages' => $paginator->lastPage()
        ];
        
        return Response::success($data, '获取用户列表成功', 200);
    }

    public function updateUserDetails(Request $request)
    {
        $data = $request->validate([
            'id' => 'required|integer',
            'username' => 'required|string',
            'password' => 'nullable|string',
        ]);
        
        // 检查是否存在相同用户名（排除当前用户）
        $existingUser = DawnUser::where('dawn_name', $data['username'])
            ->where('dawn_id', '!=', $data['id'])
            ->first();
            
        if ($existingUser) {
            return Response::error('用户信息修改失败用户名已存在', 400);
        }
        
        $user = DawnUser::where('dawn_id', $data['id'])->first();
        if($user){
            $user->dawn_name = $data['username'];
            if(isset($data['password']) && !empty($data['password'])){
                $user->dawn_password = Hash::make($data['password']);
            }
            if($data['id'] === 1){
                $user->dawn_Status = 0;
            }
            $user->save();
            return Response::success(null, '用户信息修改成功', 200);
        }
        return Response::error('用户不存在', 404);
    }

    public function deleteUserDetails(Request $request, $status)
    {
        $data = $request->validate([
            'ids' => 'required|array',
        ]);
        
        $ids = $data['ids'];
        
        // 检查是否包含id为1的用户
        if (in_array(1, $ids)) {
            return Response::error('不允许对超级管理员进行操作', 403);
        }

        // 开始数据库事务
        DB::beginTransaction();
        try {
            if($status == 3){   
                // 先删除关联的智慧教育用户数据
                DawnZhjyUser::whereIn('dawn_id', $ids)->delete();
                // 再删除基础用户数据
                $user = DawnUser::whereIn('dawn_id', $ids)->delete();
            } else {
                // 更新用户状态
                $user = DawnUser::whereIn('dawn_id', $ids)->update(['dawn_Status' => $status]);
            }

            if($user){
                DB::commit();
                return Response::success(null, '操作成功', 200);
            } else {
                DB::rollBack();
                return Response::error('操作失败', 500);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return Response::error('操作失败：' . $e->getMessage(), 500);
        }
    }


}